const express = require('express');
const router = express.Router();
const { pool } = require('../config/database');
const jwt = require('jsonwebtoken');

// JWT验证中间件
const verifyToken = (req, res, next) => {
  const token = req.headers.authorization?.replace('Bearer ', '');
  
  if (!token) {
    return res.json({
      code: '0',
      msg: '请先登录',
      result: null
    });
  }
  
  try {
    const decoded = jwt.verify(token, 'xiaotuxian_secret_key_2024');
    const userInfo = JSON.parse(decoded.sub);
    req.userId = userInfo.id;
    next();
  } catch (error) {
    return res.json({
      code: '0',
      msg: 'token无效',
      result: null
    });
  }
};

// 加入购物车 POST /member/cart
router.post('/member/cart', verifyToken, async (req, res) => {
  try {
    const { skuId, count } = req.body;
    const userId = req.userId;
    
    if (!skuId || !count) {
      return res.json({
        code: '0',
        msg: '参数不完整',
        result: null
      });
    }
    
    // 首先查询商品信息
    const goodsQuery = `
      SELECT g.goods_name as name, g.goods_picture as picture, g.goods_price as price, g.goods_price as oldPrice, 100 as stock
      FROM sys_goods g 
      WHERE g.goods_id = ?
    `;
    
    const [goodsResult] = await pool.execute(goodsQuery, [skuId]);
    
    if (goodsResult.length === 0) {
      return res.json({
        code: '0',
        msg: '商品不存在',
        result: null
      });
    }
    
    const goods = goodsResult[0];
    
    // 检查购物车中是否已存在该商品
    const checkQuery = 'SELECT * FROM sys_cart WHERE userId = ? AND skuId = ?';
    const [existingCart] = await pool.execute(checkQuery, [userId, skuId]);
    
    if (existingCart.length > 0) {
      // 更新数量
      const updateQuery = `
        UPDATE sys_cart 
        SET count = count + ?, updateTime = CURRENT_TIMESTAMP 
        WHERE userId = ? AND skuId = ?
      `;
      await pool.execute(updateQuery, [count, userId, skuId]);
    } else {
      // 新增购物车记录
      const insertQuery = `
        INSERT INTO sys_cart (
          userId, skuId, name, picture, price, nowPrice, nowOriginalPrice, 
          stock, count, selected, isEffective, isCollect
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, 0)
      `;
      
      await pool.execute(insertQuery, [
        userId, skuId, goods.name, goods.picture, 
        goods.price, goods.price, goods.oldPrice || goods.price,
        goods.stock, count
      ]);
    }
    
    res.json({
      code: '1',
      msg: '加入购物车成功',
      result: null
    });
    
  } catch (error) {
    console.error('加入购物车失败:', error);
    res.json({
      code: '0',
      msg: '加入购物车失败',
      result: null
    });
  }
});

// 获取购物车列表 GET /member/cart
router.get('/member/cart', verifyToken, async (req, res) => {
  try {
    const userId = req.userId;
    
    const query = `
      SELECT 
        id, skuId, name, attrsText, specs, picture, 
        price, nowPrice, nowOriginalPrice, selected, 
        stock, count, isEffective, discount, isCollect, postFee
      FROM sys_cart 
      WHERE userId = ? AND isEffective = 1
      ORDER BY createTime DESC
    `;
    
    const [cartList] = await pool.execute(query, [userId]);
    
    // 处理specs字段（JSON格式）
    const processedCartList = cartList.map(item => {
      let specs = [];
      try {
        if (item.specs && item.specs.trim() !== '') {
          specs = JSON.parse(item.specs);
        }
      } catch (e) {
        console.log('JSON解析错误:', e.message, '原始数据:', item.specs);
        specs = [];
      }
      
      return {
        ...item,
        specs: specs,
        selected: Boolean(item.selected),
        isEffective: Boolean(item.isEffective),
        isCollect: Boolean(item.isCollect)
      };
    });
    
    res.json({
      code: '1',
      msg: '操作成功',
      result: processedCartList
    });
    
  } catch (error) {
    console.error('获取购物车列表失败:', error);
    res.json({
      code: '0',
      msg: '获取购物车列表失败',
      result: null
    });
  }
});

// 删除购物车 DELETE /member/cart
router.delete('/member/cart', verifyToken, async (req, res) => {
  try {
    const { ids } = req.body;
    const userId = req.userId;
    
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return res.json({
        code: '0',
        msg: '请选择要删除的商品',
        result: null
      });
    }
    
    // 构建删除查询
    const placeholders = ids.map(() => '?').join(',');
    const deleteQuery = `
      DELETE FROM sys_cart 
      WHERE userId = ? AND id IN (${placeholders})
    `;
    
    const [result] = await pool.execute(deleteQuery, [userId, ...ids]);
    
    if (result.affectedRows > 0) {
      res.json({
        code: '1',
        msg: '删除成功',
        result: null
      });
    } else {
      res.json({
        code: '0',
        msg: '删除失败，商品不存在',
        result: null
      });
    }
    
  } catch (error) {
    console.error('删除购物车失败:', error);
    res.json({
      code: '0',
      msg: '删除购物车失败',
      result: null
    });
  }
});

// 合并购物车 POST /member/cart/merge
router.post('/member/cart/merge', verifyToken, async (req, res) => {
  try {
    const cartData = req.body;
    const userId = req.userId;
    
    if (!Array.isArray(cartData) || cartData.length === 0) {
      return res.json({
        code: '0',
        msg: '购物车数据不能为空',
        result: null
      });
    }
    
    // 开始事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();
    
    try {
      for (const item of cartData) {
        const { skuId, count } = item;
        
        if (!skuId || !count) continue;
        
        // 检查是否已存在
        const [existing] = await connection.execute(
          'SELECT id, count FROM sys_cart WHERE userId = ? AND skuId = ?',
          [userId, skuId]
        );
        
        if (existing.length > 0) {
          // 更新数量
          await connection.execute(
            'UPDATE sys_cart SET count = count + ? WHERE userId = ? AND skuId = ?',
            [count, userId, skuId]
          );
        } else {
          // 查询商品信息并插入
          const [goodsResult] = await connection.execute(
            'SELECT goods_name as name, goods_picture as picture, goods_price as price, goods_price as oldPrice, 100 as stock FROM sys_goods WHERE goods_id = ?',
            [skuId]
          );
          
          if (goodsResult.length > 0) {
            const goods = goodsResult[0];
            await connection.execute(`
              INSERT INTO sys_cart (
                userId, skuId, name, picture, price, nowPrice, nowOriginalPrice,
                stock, count, selected, isEffective, isCollect
              ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, 0)
            `, [
              userId, skuId, goods.name, goods.picture,
              goods.price, goods.price, goods.oldPrice || goods.price,
              goods.stock, count
            ]);
          }
        }
      }
      
      await connection.commit();
      connection.release();
      
      res.json({
        code: '1',
        msg: '合并购物车成功',
        result: null
      });
      
    } catch (error) {
      await connection.rollback();
      connection.release();
      throw error;
    }
    
  } catch (error) {
    console.error('合并购物车失败:', error);
    res.json({
      code: '0',
      msg: '合并购物车失败',
      result: null
    });
  }
});

module.exports = router;